/**
 * 提醒功能API
 * 完全使用本地存储，不依赖后端API
 */
import { getCurrentDate } from '../utils/date.js'

/**
 * 获取提醒列表
 * @param {Object} params 查询参数，如类型、状态等
 * @returns {Promise} Promise对象
 */
export const getReminders = (params = {}) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 从本地存储获取
      let reminders = uni.getStorageSync('reminders') || []
      
      // 按类型过滤
      if (params.type) {
        reminders = reminders.filter(reminder => reminder.type === params.type)
      }
      
      // 按状态过滤
      if (params.active !== undefined) {
        reminders = reminders.filter(reminder => reminder.active === params.active)
      }
      
      // 按照时间升序排序
      reminders.sort((a, b) => {
        return a.time.localeCompare(b.time)
      })
      
      resolve({
        code: 0,
        message: '获取成功',
        data: reminders
      })
    }, 50) // 减少延迟，提高响应速度
  })
}

/**
 * 获取提醒详情
 * @param {String|Number} id 提醒ID
 * @returns {Promise} Promise对象
 */
export const getReminderDetail = (id) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const reminders = uni.getStorageSync('reminders') || []
      const reminder = reminders.find(item => item.id == id)
      
      if (reminder) {
        resolve({
          code: 0,
          message: '获取成功',
          data: reminder
        })
      } else {
        resolve({
          code: 404,
          message: '提醒不存在',
          data: null
        })
      }
    }, 50)
  })
}

/**
 * 添加提醒
 * @param {Object} reminder 提醒数据
 * @returns {Promise} Promise对象
 */
export const addReminder = (reminder) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 从本地存储获取
      const reminders = uni.getStorageSync('reminders') || []
      
      // 生成ID
      const maxId = reminders.length > 0 ? Math.max(...reminders.map(r => r.id || 0)) : 0
      const newId = maxId + 1
      
      // 生成新提醒
      const newReminder = {
        ...reminder,
        id: newId,
        createTime: new Date().toISOString()
      }
      
      // 将提醒添加到本地存储
      reminders.unshift(newReminder)
      uni.setStorageSync('reminders', reminders)
      
      resolve({
        code: 0,
        message: '添加成功',
        data: newReminder
      })
    }, 50)
  })
}

/**
 * 更新提醒
 * @param {String|Number} id 提醒ID
 * @param {Object} reminder 提醒数据
 * @returns {Promise} Promise对象
 */
export const updateReminder = (id, reminder) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 从本地存储获取提醒
      const reminders = uni.getStorageSync('reminders') || []
      const index = reminders.findIndex(item => item.id == id)
      
      if (index !== -1) {
        // 更新提醒
        const updatedReminder = {
          ...reminders[index],
          ...reminder,
          id: id
        }
        
        reminders[index] = updatedReminder
        
        // 保存回本地存储
        uni.setStorageSync('reminders', reminders)
        
        resolve({
          code: 0,
          message: '更新成功',
          data: updatedReminder
        })
      } else {
        resolve({
          code: 404,
          message: '提醒不存在',
          data: null
        })
      }
    }, 50)
  })
}

/**
 * 删除提醒
 * @param {String|Number} id 提醒ID
 * @returns {Promise} Promise对象
 */
export const deleteReminder = (id) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 从本地存储获取提醒
      const reminders = uni.getStorageSync('reminders') || []
      const index = reminders.findIndex(item => item.id == id)
      
      if (index !== -1) {
        // 删除提醒
        reminders.splice(index, 1)
        
        // 保存回本地存储
        uni.setStorageSync('reminders', reminders)
        
        resolve({
          code: 0,
          message: '删除成功',
          data: null
        })
      } else {
        resolve({
          code: 404,
          message: '提醒不存在',
          data: null
        })
      }
    }, 50)
  })
}

/**
 * 切换提醒状态（启用/禁用）
 * @param {String|Number} id 提醒ID
 * @param {Boolean} active 是否启用
 * @returns {Promise} Promise对象
 */
export const toggleReminderStatus = (id, active) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 从本地存储获取提醒
      const reminders = uni.getStorageSync('reminders') || []
      const index = reminders.findIndex(item => item.id == id)
      
      if (index !== -1) {
        // 更新状态
        reminders[index].active = active
        
        // 保存回本地存储
        uni.setStorageSync('reminders', reminders)
        
        resolve({
          code: 0,
          message: active ? '提醒已启用' : '提醒已禁用',
          data: reminders[index]
        })
      } else {
        resolve({
          code: 404,
          message: '提醒不存在',
          data: null
        })
      }
    }, 50)
  })
}

/**
 * 获取今日提醒
 * @returns {Promise} Promise对象
 */
export const getTodayReminders = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 从本地存储获取提醒
      let reminders = uni.getStorageSync('reminders') || []
      
      // 筛选今日提醒
      // 对于每日重复的，或每周重复且今天符合的，或一次性且今天的
      const today = new Date()
      const todayString = today.toISOString().split('T')[0]
      const dayOfWeek = today.getDay() === 0 ? 7 : today.getDay() // 获取星期几，转换为1-7
      
      reminders = reminders.filter(reminder => {
        // 筛选启用的提醒
        if (!reminder.active) return false
        
        // 每天重复的提醒
        if (reminder.repeat === 'daily') return true
        
        // 每周重复的提醒，检查今天是否在重复日期中
        if (reminder.repeat === 'weekly') {
          return reminder.repeatDays.includes(dayOfWeek)
        }
        
        // 一次性提醒，检查是否是今天的
        if (reminder.repeat === 'once') {
          // 一次性提醒有日期字段date
          return reminder.date === todayString
        }
        
        return false
      })
      
      // 按照时间排序
      reminders.sort((a, b) => {
        return a.time.localeCompare(b.time)
      })
      
      resolve({
        code: 0,
        message: '获取成功',
        data: reminders
      })
    }, 50)
  })
}

/**
 * 获取下一个提醒
 * @returns {Promise} Promise对象
 */
export const getNextReminder = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 获取提醒列表
      const reminders = uni.getStorageSync('reminders') || []
      
      // 过滤出已启用的提醒
      const activeReminders = reminders.filter(r => r.active)
      
      if (activeReminders.length === 0) {
        resolve({
          code: 200,
          message: '没有可用的提醒',
          data: null
        })
        return
      }
      
      // 获取当前时间
      const now = new Date()
      const currentHour = now.getHours()
      const currentMinute = now.getMinutes()
      const currentTime = `${currentHour.toString().padStart(2, '0')}:${currentMinute.toString().padStart(2, '0')}`
      const currentDayOfWeek = now.getDay() === 0 ? 7 : now.getDay() // 转为1-7
      const todayString = now.toISOString().split('T')[0]
      
      // 找出今天适用的提醒
      let todayReminders = activeReminders.filter(reminder => {
        if (reminder.repeat === 'daily') return true
        if (reminder.repeat === 'weekly' && reminder.repeatDays.includes(currentDayOfWeek)) return true
        if (reminder.repeat === 'once' && reminder.date === todayString) return true
        return false
      })
      
      if (todayReminders.length === 0) {
        resolve({
          code: 200,
          message: '今天没有可用的提醒',
          data: null
        })
        return
      }
      
      // 按时间排序
      todayReminders.sort((a, b) => a.time.localeCompare(b.time))
      
      // 找出下一个要执行的提醒
      let nextReminder = null
      
      // 先找今天还未到时间的提醒
      for (const reminder of todayReminders) {
        if (reminder.time > currentTime) {
          nextReminder = reminder
          break
        }
      }
      
      // 如果没有找到，则返回今天的第一个提醒（循环到明天）
      if (!nextReminder && todayReminders.length > 0) {
        nextReminder = todayReminders[0]
      }
      
      resolve({
        code: 0,
        message: '获取成功',
        data: nextReminder
      })
    }, 50)
  })
}

/**
 * 初始化提醒数据
 * 在应用首次使用时添加一些示例提醒
 */
export const initReminderData = () => {
  // 检查是否已经初始化
  const reminders = uni.getStorageSync('reminders')
  
  // 如果已有数据，不需要初始化
  if (reminders && reminders.length > 0) {
    return
  }
  
  // 创建示例提醒
  const now = new Date()
  const today = now.toISOString().split('T')[0]
  let hour = now.getHours()
  let minute = now.getMinutes() + 2 // 设置为当前时间后2分钟
  
  if (minute >= 60) {
    minute = minute - 60
    hour = (hour + 1) % 24
  }
  
  const time = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
  
  // 创建示例数据
  const sampleReminders = [
    {
      id: 1,
      title: '按时服药',
      desc: '早上需要服用降糖药物',
      type: 'medicine',
      time: '07:30',
      repeat: 'daily',
      repeatText: '每天',
      active: true,
      createTime: new Date().toISOString()
    },
    {
      id: 2,
      title: '空腹测血糖',
      desc: '早餐前测量空腹血糖',
      type: 'bloodSugar',
      time: '07:00',
      repeat: 'daily',
      repeatText: '每天',
      active: true,
      createTime: new Date().toISOString()
    },
    {
      id: 3,
      title: '午餐后测血糖',
      desc: '午餐后两小时测量血糖',
      type: 'bloodSugar',
      time: '13:30',
      repeat: 'daily',
      repeatText: '每天',
      active: true,
      createTime: new Date().toISOString()
    },
    {
      id: 4,
      title: '晚间散步',
      desc: '晚饭后进行30分钟轻度运动',
      type: 'exercise',
      time: '19:30',
      repeat: 'weekly',
      repeatDays: [1, 3, 5], // 周一、周三、周五
      repeatText: '每周 周一、周三、周五',
      active: true,
      createTime: new Date().toISOString()
    },
    {
      id: 5,
      title: '医院复诊',
      desc: '三个月定期复查',
      type: 'other',
      time: '09:00',
      repeat: 'once',
      date: today, // 设为今天用于演示
      repeatText: today,
      active: true,
      createTime: new Date().toISOString()
    },
    {
      id: 6,
      title: '即将到来的提醒',
      desc: '用于演示提醒通知',
      type: 'other',
      time: time, // 设为当前时间后两分钟
      repeat: 'once',
      date: today,
      repeatText: today,
      active: true,
      createTime: new Date().toISOString()
    }
  ]
  
  // 保存到本地存储
  uni.setStorageSync('reminders', sampleReminders)
  
  console.log('初始化提醒数据完成')
}

export default {
  getReminders,
  getReminderDetail,
  addReminder,
  updateReminder,
  deleteReminder,
  toggleReminderStatus,
  getTodayReminders,
  getNextReminder,
  initReminderData
} 